<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>IP属地</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #container {
      width: 100%;
      height: 100vh;
    }
    .custom-content-marker {
      position: relative;
      width: 25px;
      height: 34px;
    }
    .custom-content-marker img {
      width: 100%;
      height: 100%;
    }
  </style>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: 'aa3291252ce85809fde85262387074f2',
    }
  </script>
  <script type="text/javascript"
          src="https://webapi.amap.com/maps?v=1.4.15&key=7a05156c06797a78b15386a5ba74377e">
  </script>
</head>

<body>
  <div id="container"></div>
  <script>
    const map = new AMap.Map("container", {
      // 级别
      zoom: 15,
      // 中心点坐标
      center: [116.397428, 39.90923]
    })
    let h5Port
    window.addEventListener("message", (event) => {
      if (event.data == "__init_port__") {
        h5Port = event.ports[0]
        // 接收鸿蒙发过来的消息
        h5Port.onmessage = (event) => {
          // 获取经纬度
          let locationArr = event.data
          if (typeof (locationArr) == "string") {
            locationArr = JSON.parse(locationArr)
            // 设置当前位置
            map.setZoomAndCenter(15, locationArr)
            // 添加标记
            const markerContent = `<div class="custom-content-marker">
                <img src="https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">
              </div>`
            const marker = new AMap.Marker({
              position: new AMap.LngLat(...locationArr),
              content: markerContent,
              offset: new AMap.Pixel(-13, -30)
            })
            map.add(marker)
            // 根据经纬度查询省份
            map.plugin('AMap.Geocoder', function () {
              var geocoder = new AMap.Geocoder()
              geocoder.getAddress(locationArr, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                  // 向鸿蒙发送消息
                  h5Port.postMessage(result.regeocode.addressComponent.province)
                }
              })
            })
          }
        }
      }
    })
  </script>
</body>

</html>